package com.hqyj.paimaisys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hqyj.paimaisys.model.Auction;
import com.hqyj.paimaisys.model.Huiyuan;
import com.hqyj.paimaisys.service.AuctionService;
import com.hqyj.paimaisys.service.HuiyuanService;
import com.hqyj.paimaisys.util.DateUtil;
import com.hqyj.paimaisys.web.ResponseResult;
import com.hqyj.paimaisys.web.SendPriceWebsocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2024-10-20
 */
@RestController
@RequestMapping("/auction")
public class AuctionController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    AuctionService auctionService;

    @Autowired
    HuiyuanService huiyuanService;

    @Value("${pagesize}")
    int pagesize;

    //400异常： 请求中的参数类型和方法中的参数类型不匹配
    @RequestMapping("page")
    public ResponseResult<Page> page(String searchname,String searchtype,
                                     @RequestParam(defaultValue = "1") Integer pageno){
        QueryWrapper<Auction> wrapper = new QueryWrapper<Auction>();
        if(StringUtils.isNotBlank(searchtype)){
            wrapper.eq("tid", Integer.parseInt(searchtype));
        }
        wrapper.like(StringUtils.isNotBlank(searchname), "gname", searchname);

        Page<Auction> page = new Page<Auction>(pageno,pagesize);

        Page<Auction> result = auctionService.page(page,wrapper);

        System.out.println("records: " + result.getRecords());
        System.out.println("pages: " + result.getPages());
        System.out.println("total:" + result.getTotal());
        return ResponseResult.success(result);
    }

     @RequestMapping("/fabu")
     public ResponseResult<String> fabu(MultipartFile pic, Auction auction, HttpServletRequest request) throws IOException {
         //1.把图片保存到nginx服务器   uuid.jpg

         System.out.println(pic.getOriginalFilename());
         System.out.println(pic.getOriginalFilename().lastIndexOf("."));
         String ext = pic.getOriginalFilename().substring(pic.getOriginalFilename().lastIndexOf("."));
         String filename = UUID.randomUUID().toString() + ext;
         //http://localhost:9090/images/filename
         File dest = new File("D:\\nginx\\html\\images", filename);
         pic.transferTo(dest);

         //2.修改auction请求参数, 补充页面没有提交的属性值， 比如上传图片的路径
         // 图片路径  状态 发布者  发布者角色
         auction.setGpic(filename);  //文件名，不能写物理路径
         auction.setState(Auction.STATUS_NO_SHENHE);
         //请求头中保存了token, redis中 根据token得到hid
         String token = request.getHeader("token");
         String hid = redisTemplate.opsForValue().get(token);
         auction.setCreaterid(hid);
         auction.setCflag(Auction.ROLE_HUIYUAN);
         //3.把发布的拍品保存到数据库中
         auctionService.save(auction);
         return ResponseResult.success();

     }

     @RequestMapping("getone")
     public ResponseResult<Auction> getOne(Integer aid){

         Auction auction = auctionService.getById(aid);
         return ResponseResult.success(auction);
     }

    /**
     * 立即竞拍
     * 1. 会员余额 < 保证金， 不能竞拍
     * 2. 出价
     *      2.1 如果是第一个竞拍者， 出价 > 起步价
     *      2.2 如果不是第一个竞拍者    出价 > 目前的最新价 + 增长价
     * @param aid ： 拍品ID
     * @param nprice ： 竞拍价
     * @return
     */

    @RequestMapping("/jingpai")
    public ResponseResult<String> jingpai(Integer aid, Integer nprice, HttpServletRequest request){
         String token = request.getHeader("token");
         String hid = redisTemplate.opsForValue().get(token);
         Huiyuan  huiyuan = huiyuanService.getById(hid);


         // 查询拍品信息
         Auction auction = auctionService.getById(aid);

         //竞拍时间必须在起止时间段内
         String stime = auction.getStime() + " 08:00:00";
         String etime = auction.getEtime() + " 18:00:00";
         Date date = new Date();
         boolean flag = DateUtil.isValidTime(date,stime,etime);
         if(flag == false){
             return ResponseResult.error("非法时间抢购");
         }
         if(huiyuan.getHyue() < auction.getAbmoney()){
             return ResponseResult.error("余额不足，请先充值");
         }
         if(auction.getHid() == null){
             if(nprice < auction.getBprice()){
                 return ResponseResult.error("出价太低");
             }
         }

         else {
             if (nprice < (auction.getNprice() + auction.getIncrease())) {
                 return ResponseResult.error("出价太低");
             }
         }
         //通过以上验证， 启动竞拍
         auctionService.jingpai(aid, nprice, hid);

         // 竞拍成功， 给围观者发送最新价格 ， 参数 aid  nprice hid
         SendPriceWebsocket.sendMsg(aid, hid, nprice);
         return ResponseResult.success("竞拍成功");

     }

     @RequestMapping("/shenhelist")
     public ResponseResult<Page> shenhelist(Integer pagenum){
        // select * from auction where state = 2
         QueryWrapper<Auction> queryWrapper = new QueryWrapper<Auction>();
         queryWrapper.eq("state", Auction.STATUS_NO_SHENHE);

         Page<Auction> page = new Page<Auction>(pagenum, pagesize);
         return ResponseResult.success(auctionService.page(page, queryWrapper));
     }

     @RequestMapping("/shenhe")
     public ResponseResult<String> shenhe(Integer aid, Integer state){
         UpdateWrapper<Auction> auctionUpdateWrapper = new UpdateWrapper<Auction>();
         auctionUpdateWrapper.set("state", state);
         auctionUpdateWrapper.eq("aid", aid);
         auctionService.update(auctionUpdateWrapper);
         return  ResponseResult.success();
     }
}

